local cuanhe = fk.CreateSkill{
  name = "xiaobai__cuanhe",
}

Fk:loadTranslationTable{
  ["xiaobai__cuanhe"] = "攒和",
  [":xiaobai__cuanhe"] = "当你需要使用基本牌时，你可以依次与手牌数相差一、二、三的其他角色交换手牌，若因此交换了三次，你视为使用之；若你手牌数未减少，此技能本轮失效。",

  ["#xiaobai__cuanhe"] = "攒和：你可以和一名手牌数相差 %arg 的其他角色交换手牌",
  ["@@cuanhe"] = "攒和失效"
}

local U = require "packages.utility.utility"

cuanhe:addEffect("viewas", {
  pattern = ".|.|.|.|.|basic",
  interaction = function(self, player)
    local all_names = Fk:getAllCardNames("b")
    local names = player:getViewAsCardNames(cuanhe.name, all_names, nil)
    if #names == 0 then return end
    return UI.CardNameBox {choices = names, all_names = all_names}
  end,
  view_as = function(self, player, cards)
    if self.interaction.data == nil or self.interaction.data == "" then return end
    local card = Fk:cloneCard(self.interaction.data)
    card.skillName = cuanhe.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    local able = 0
    local card_preuse_num = player:getHandcardNum()
    for i = 1,3,1 do
      local valid_targets = table.filter(room:getOtherPlayers(player, false), function (p)
        return math.abs(player:getHandcardNum() - p:getHandcardNum()) == i
      end)
      if #valid_targets == 0 then break end
      local tos = room:askToChoosePlayers(player, {
        min_num = 1,
        max_num = 1,
        targets = valid_targets,
        skill_name = cuanhe.name,
        prompt ="#xiaobai__cuanhe:::"..U.ConvertNumber(i),
      })
      if #tos == 0 then break end
      room:swapAllCards(player, {player, tos[1]}, cuanhe.name)
      able = able + 1
    end
    if player:getHandcardNum() > card_preuse_num or player:getHandcardNum() == card_preuse_num then
      room:invalidateSkill(player, cuanhe.name, "-round")
    end
    if able < 3 then return cuanhe.name end
  end,
  enabled_at_play = function(self, player)
    local all_names = Fk:getAllCardNames("b")
    local names = player:getViewAsCardNames(cuanhe.name, all_names, nil)
    if #names == 0 then return end
    return true
  end,
  enabled_at_response = function(self, player, response)
    local all_names = Fk:getAllCardNames("b")
    local names = player:getViewAsCardNames(cuanhe.name, all_names, nil)
    if #names == 0 then return end
    return not response
  end,
})

return cuanhe